import 'dart:async';

import 'package:flutter_axrjc/datasource/network/api/KnowledgeApi.dart';
import 'package:flutter_axrjc/datasource/network/bean/ArticleBean.dart';
import 'package:flutter_axrjc/datasource/network/bean/ArticleTabBean.dart';
import 'package:flutter_axrjc/datasource/network/bean/EventBean.dart';
import 'package:flutter_axrjc/datasource/network/request/exp.dart';
import 'package:flutter_axrjc/main.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'state.dart';

class KnowledgeLogic extends GetxController {
  final KnowledgeState state = KnowledgeState();
  var page = 1;

  StreamSubscription<EventBean>? listener;

  var refreshController = RefreshController(initialRefresh: true);
  @override
  void onInit() {
    super.onInit();
    listener = eventBus.on<EventBean>().listen((event) {
      if (event.type == EventType.refreshMyLights) {
        getTopThree();
      }
    });
  }

  @override
  void onClose() {
    listener?.cancel();
  }

  Future<void> getTopThree() async {
    try {
      state.tabs.clear();
      state.topThree.addAll(await KnowledgeApi.getTopThree(
          limit: "3", page: '1', categoryId: '', ifText: true));
      state.tabs.addAll(await KnowledgeApi.getTabsPage(page: '1'));
      refreshTabs();
    } on ApiException catch (e) {
      EasyLoading.showToast(e.message);
    } catch (e) {
      print(e);
    }
    refreshController.refreshCompleted();
  }

  Future<void> refreshTabs() async {
    state.typeList.clear();
    for (var element in state.tabs) {
      state.typeList.add(TypeBean(
          tab: element,
          three: await KnowledgeApi.getTopThree(
              limit: "3",
              page: '1',
              categoryId: '${element.categoryId}',
              ifText: true)));
    }
  }
}

class TypeBean {
  final ArticleTabBean tab;
  final List<ArticleBean> three;

  TypeBean({required this.tab, required this.three});
}
